<template>
  <div class="settings-container">
    <div class="settings-header">
      <button @click="goBack" class="back-button">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M19 12H5M12 19l-7-7 7-7"/>
        </svg>
        返回
      </button>
      <h1>设置</h1>
      <p>管理应用数据和存储设置</p>
    </div>

    <div class="settings-content">
      <!-- 主题设置 -->
      <div class="setting-section">
        <h2>主题设置</h2>
        
        <div class="theme-selector">
          <div class="theme-options">
            <div 
              v-for="theme in themes" 
              :key="theme.id"
              class="theme-option"
              :class="{ active: selectedTheme === theme.id }"
              :data-theme-id="theme.id"
              @click="selectTheme(theme.id)"
              :title="theme.description"
            >
              <div class="theme-preview">
                <div class="theme-colors">
                  <div 
                    v-for="color in theme.colors" 
                    :key="color"
                    class="theme-color" 
                    :style="{ backgroundColor: color }"
                  ></div>
                </div>
                <div class="theme-info">
                  <div class="theme-name">{{ theme.name }}</div>
                  <div class="theme-description">{{ theme.description }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="theme-tip">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10"></circle>
              <path d="M12 16v-4"></path>
              <path d="M12 8h.01"></path>
            </svg>
            <span>主题设置会自动保存，重新打开应用时会保持您的选择</span>
          </div>
        </div>
      </div>

      <!-- 数据管理 -->
      <div class="setting-section">
        <h2>数据管理</h2>
        
        <!-- 状态提示区域 -->
        <div v-if="dataOperationMessage" class="data-operation-message" :class="dataOperationMessageType">
          <svg v-if="dataOperationMessageType === 'success'" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 12l2 2 4-4"></path>
            <circle cx="12" cy="12" r="10"></circle>
          </svg>
          <svg v-else-if="dataOperationMessageType === 'error'" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="15" y1="9" x2="9" y2="15"></line>
            <line x1="9" y1="9" x2="15" y2="15"></line>
          </svg>
          <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"></circle>
            <path d="M12 8v4"></path>
            <path d="M12 16h.01"></path>
          </svg>
          <span>{{ dataOperationMessage }}</span>
        </div>
        
        <div class="setting-item">
          <div class="setting-info">
            <h3>导出数据</h3>
            <p>将所有清单和任务数据导出到本地文件</p>
          </div>
          <button @click="exportData" :disabled="exporting" class="btn-primary">
            {{ exporting ? '导出中...' : '导出数据' }}
          </button>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>导入数据</h3>
            <p>从本地文件导入数据进行恢复</p>
          </div>
          <button @click="importData" :disabled="importing" class="btn-secondary">
            {{ importing ? '导入中...' : '导入数据' }}
          </button>
        </div>

        <div class="setting-item danger">
          <div class="setting-info">
            <h3>清空数据</h3>
            <p>删除所有清单和任务数据</p>
          </div>
          <button @click="showClearConfirm = true" class="btn-danger">
            清空数据
          </button>
        </div>
      </div>

      <!-- 番茄钟设置 -->
      <div class="setting-section">
        <h2>番茄钟设置</h2>
        
        <div class="setting-item">
          <div class="setting-info">
            <h3>任务完成提示音</h3>
            <p>选择任务完成时播放的提示音</p>
          </div>
          <div class="sound-selector">
            <select v-model="selectedSound" @change="onSoundChange" class="sound-select">
              <option value="bell.mp3">经典铃声</option>
              <option value="bell-notification.mp3">通知铃声</option>
              <option value="ding.mp3">叮咚声</option>
              <option value="ding2.mp3">叮咚声2</option>
              <option value="doorbell.mp3">门铃声</option>
              <option value="electronic-doorbell.mp3">电子门铃</option>
            </select>
            <button @click="previewSound" class="btn-secondary preview-btn">
              {{ isPlaying ? '停止' : '试听' }}
            </button>
          </div>
        </div>
      </div>

      <!-- AI 模型设置 -->
      <div class="setting-section">
        <h2>AI 模型设置</h2>
        <div class="config-description">
          <p>配置您的大模型 API 信息以使用智能清单功能。详细配置说明请参考：
            <a href="https://www.ynaa.net/topics/8" target="_blank" class="config-link">AI 模型配置指南</a>
          </p>
        </div>
        
        <div class="setting-item">
          <div class="setting-info">
            <h3>API 端点</h3>
            <p>设置大模型 API 的请求地址</p>
          </div>
          <div class="ai-config-input">
            <input 
              v-model="aiConfig.apiUrl" 
              type="text" 
              placeholder="https://ark.cn-beijing.volces.com/api/v3/chat/completions"
              class="config-input"
              @blur="saveAiConfig"
            />
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>模型名称</h3>
            <p>选择要使用的大模型</p>
          </div>
          <div class="ai-config-input">
            <select 
              v-model="aiConfig.modelName" 
              class="config-input model-select"
              @change="saveAiConfig"
              :disabled="loadingModels"
            >
              <option value="" disabled>{{ loadingModels ? '加载中...' : '请选择模型' }}</option>
              <option 
                v-for="model in availableModels" 
                :key="model.id" 
                :value="model.id"
              >
                {{ model.name }}
              </option>
            </select>
            <button 
              @click="refreshModels" 
              :disabled="loadingModels || !aiConfig.apiUrl || !aiConfig.apiKey"
              class="btn-secondary refresh-btn"
              :title="loadingModels ? '加载中...' : '刷新模型列表'"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" :class="{ 'rotating': loadingModels }">
                <polyline points="23 4 23 10 17 10"></polyline>
                <polyline points="1 20 1 14 7 14"></polyline>
                <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"></path>
              </svg>
            </button>
          </div>
          <!-- 模型获取错误信息显示 -->
          <div v-if="modelsError" class="error-info">
            <p class="error-message">
              <strong>错误:</strong> 
              <span v-if="modelsError.faqUrl" v-html="formatMessageWithLink(modelsError.message, modelsError.faqUrl)"></span>
              <span v-else>{{ modelsError.message }}</span>
            </p>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>API Key</h3>
            <p>您的大模型 API 密钥（将安全存储）</p>
          </div>
          <div class="ai-config-input">
            <input 
              v-model="aiConfig.apiKey" 
              :type="showApiKey ? 'text' : 'password'"
              placeholder="请输入您的 API Key"
              class="config-input"
              @blur="saveAiConfig"
            />
            <button 
              @click="showApiKey = !showApiKey" 
              class="btn-secondary toggle-btn"
              :title="showApiKey ? '隐藏密钥' : '显示密钥'"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path v-if="!showApiKey" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                <circle v-if="!showApiKey" cx="12" cy="12" r="3"></circle>
                <path v-if="showApiKey" d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
                <line v-if="showApiKey" x1="1" y1="1" x2="23" y2="23"></line>
              </svg>
            </button>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>配置状态</h3>
            <p>{{ aiConfigStatus }}</p>
            <div v-if="balanceInfo.status" class="balance-info" :class="balanceInfo.status">
              <p class="balance-status" :class="balanceInfo.status">
                <strong>账户状态:</strong> 
                <span v-if="balanceInfo.faqUrl" v-html="formatMessageWithLink(balanceInfo.message, balanceInfo.faqUrl)"></span>
                <span v-else>{{ balanceInfo.message }}</span>
              </p>
              <div v-if="balanceInfo.usage" class="usage-info">
                <small>最近调用: {{ balanceInfo.usage.total_tokens }} tokens</small>
              </div>
            </div>
          </div>
          <div class="config-actions">
            <button @click="testAiConfig" :disabled="testingAi" class="btn-secondary">
              {{ testingAi ? '测试中...' : '测试连接' }}
            </button>
            <button 
              @click="checkBalance" 
              :disabled="checkingBalance || !aiConfig.apiUrl || !aiConfig.modelName || !aiConfig.apiKey" 
              class="btn-secondary"
            >
              {{ checkingBalance ? '查询中...' : '查询余额' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 存储信息 -->
      <div class="setting-section">
        <h2>数据存储</h2>
        <div class="setting-item">
          <div class="setting-info">
            <h3>存储方式</h3>
            <p>{{ storageType }}</p>
          </div>
        </div>
        
        <div class="setting-item" v-if="storagePath">
          <div class="setting-info">
            <h3>存储路径</h3>
            <p class="path-text">{{ storagePath }}</p>
          </div>
          <button @click="copyPath" class="btn-secondary">
            {{ copied ? '已复制' : '复制路径' }}
          </button>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>数据统计</h3>
            <p>清单: {{ todoStore.state.lists.length }} 个，任务: {{ todoStore.state.tasks.length }} 个</p>
          </div>
        </div>
      </div>

      <!-- 数据同步设置 -->
      <div class="setting-section">
        <h2>数据同步</h2>
        
        <div class="setting-item">
          <div class="setting-info">
            <h3>同步状态</h3>
            <p>{{ todoStore.state.isInitialized ? '已初始化' : '未初始化' }}</p>
            <p class="sync-time-info">最近同步: {{ lastSyncTime }}</p>
          </div>
          <div class="sync-status-indicator" :class="{ 'syncing': isSyncing }">
            <svg v-if="!isSyncing" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              <path d="M9 12l2 2 4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <svg v-else class="spinning" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M21 12A9 9 0 1 1 3 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
            <span>{{ isSyncing ? '同步中...' : '正常' }}</span>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>自动同步</h3>
            <p>应用启动和关闭时自动同步，运行期间每15分钟自动同步一次</p>
          </div>
          <div class="setting-control">
            <label class="switch">
              <input type="checkbox" v-model="autoSyncEnabled" @change="updateAutoSync">
              <span class="slider"></span>
            </label>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>定时同步</h3>
            <p>按设定的时间间隔自动同步数据</p>
          </div>
          <div class="setting-control">
            <label class="switch">
              <input type="checkbox" v-model="intervalSyncEnabled" @change="updateIntervalSync">
              <span class="slider"></span>
            </label>
          </div>
        </div>

        <div v-if="intervalSyncEnabled" class="setting-item">
          <div class="setting-info">
            <h3>同步间隔</h3>
            <p>设置自动同步的时间间隔</p>
          </div>
          <div class="setting-control">
            <select v-model="syncInterval" @change="updateSyncInterval" class="interval-select">
              <option value="15">15分钟</option>
              <option value="30">30分钟</option>
              <option value="60">1小时</option>
              <option value="180">3小时</option>
              <option value="360">6小时</option>
            </select>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <h3>立即同步</h3>
            <p>手动触发数据同步</p>
          </div>
          <button @click="handleSyncNow" :disabled="isSyncing" class="btn-primary sync-btn">
            <svg v-if="!isSyncing" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M1 4V10H7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M23 20V14H17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10M23 14L18.36 18.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <svg v-else class="spinning" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M21 12A9 9 0 1 1 3 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
            {{ isSyncing ? '同步中...' : '立即同步' }}
          </button>
        </div>
      </div>

      

      <!-- 应用信息 -->
      <div class="setting-section">
        <h2>应用信息</h2>
        <div class="setting-item">
          <div class="setting-info">
            <h3>运行环境</h3>
            <p>{{ todoStore.isElectron() ? 'Electron 桌面应用' : '浏览器 Web 应用' }}</p>
          </div>
        </div>
        
        <div class="setting-item version-info">
          <div class="setting-info">
            <h3>版本信息</h3>
            <p>当前版本: {{ currentVersion }} | 最新版本: {{ latestVersion || '检查中...' }}
              <span v-if="hasNewVersion" class="new-version-badge">有新版本</span>
            </p>
          </div>
          <div class="version-actions">
            <button @click="checkVersion" :disabled="checkingVersion" class="btn-secondary">
              {{ checkingVersion ? '检查中...' : '检查更新' }}
            </button>
            <button v-if="hasNewVersion" @click="openUpgradePage" class="btn-primary upgrade-btn">
              <svg class="upgrade-arrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M7 17L17 7M17 7H7M17 7V17"/>
              </svg>
              立即升级
            </button>
          </div>
        </div>
        <div class="setting-item">
          <div class="setting-info">
            <h3>关于我们</h3>
            <p>了解点点清单应用的详细信息</p>
          </div>
          <button @click="showAbout = true" class="btn-secondary">
            查看详情
          </button>
        </div>
      </div>

      <div style="height: 60px;"></div>
    </div>

    <!-- 确认对话框 -->
    <div v-if="showClearConfirm" class="modal-overlay" @click="showClearConfirm = false">
      <div class="modal" @click.stop>
        <h3>确认清空数据</h3>
        <p>此操作将删除所有清单和任务数据，且无法恢复。确定要继续吗？</p>
        <div class="modal-actions">
          <button @click="showClearConfirm = false" class="btn-secondary">取消</button>
          <button @click="clearAllData" class="btn-danger">确认清空</button>
        </div>
      </div>
    </div>

    <!-- 导入数据确认对话框 -->
    <div v-if="showImportConfirm" class="modal-overlay" @click="showImportConfirm = false">
      <div class="modal" @click.stop>
        <h3>确认导入数据</h3>
        <div class="import-info" v-if="importData_temp">
          <p>即将导入以下数据：</p>
          <div class="import-details">
            <div class="import-item">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M9 11H7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2h-2M9 11V9a2 2 0 1 1 4 0v2M9 11h6"></path>
              </svg>
              <span>清单：{{ importData_temp.lists?.length || 0 }} 个</span>
            </div>
            <div class="import-item">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M9 12l2 2 4-4"></path>
                <circle cx="12" cy="12" r="10"></circle>
              </svg>
              <span>任务：{{ importData_temp.tasks?.length || 0 }} 个</span>
            </div>
          </div>
          <div class="import-warning">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
              <line x1="12" y1="9" x2="12" y2="13"></line>
              <line x1="12" y1="17" x2="12.01" y2="17"></line>
            </svg>
            <span>注意：这将覆盖当前所有数据！</span>
          </div>
        </div>
        <div class="modal-actions">
          <button @click="cancelImport" class="btn-secondary">取消</button>
          <button @click="confirmImport" class="btn-primary">确认导入</button>
        </div>
      </div>
    </div>

    <!-- 关于我们对话框 -->
    <div v-if="showAbout" class="modal-overlay" @click="showAbout = false">
      <div class="modal about-modal" @click.stop>
        <div class="about-header">
          <h3>关于点点清单</h3>
          <button @click="showAbout = false" class="close-btn">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
        <div class="about-content">
          <div class="about-section">
            <h4>📋 应用简介</h4>
            <p>点点清单是一个现代化的任务管理应用，集成番茄钟、白噪音、AI 智能规划等功能，帮助您提高工作效率和专注力。</p>
            <p>本项目由 <a href="https://ynaa.net" target="_blank">YNAA.NET</a> 团队开发并完全免费开源，欢迎大家参与贡献和反馈。</p>
            <div class="warning-notice">
              <h5>⚠️ 重要提醒</h5>
              <p>本软件完全免费提供，我们会尽最大努力保护您的数据安全，但由于技术限制、服务器资源约束等因素，<strong>无法100%保证数据安全</strong>。请您定期使用导出功能备份重要数据，不要记录敏感信息，理解并接受免费软件的局限性。</p>
            </div>
          </div>
          
          <div class="about-section">
            <h4>✨ 主要功能</h4>
            <ul>
              <li><strong>智能任务管理</strong>：支持多清单、任务分类、优先级设置和智能视图</li>
              <li><strong>AI 智能规划</strong>：基于大模型的任务智能分解和时间规划建议</li>
              <li><strong>专业番茄钟</strong>：25分钟专注计时，支持自定义时长和多种提示音</li>
              <li><strong>沉浸式白噪音</strong>：内置雨声、咖啡厅、海浪等多种环境音效</li>
              <li><strong>数据统计分析</strong>：任务完成趋势、时间使用分析和效率报告</li>
              <li><strong>用户系统</strong>：支持注册登录、跨设备数据同步</li>
              <li><strong>个性化定制</strong>：8种精美主题，包括中国风、复古感等风格</li>
            </ul>
          </div>
          
          <div class="about-section">
            <h4>🛠️ 技术栈</h4>
            <div class="tech-stack">
              <span class="tech-tag">Electron 27.0.0</span>
              <span class="tech-tag">Vue 3</span>
              <span class="tech-tag">Vite 5.4.11</span>
              <span class="tech-tag">Pinia</span>
              <span class="tech-tag">Vue Router</span>
              <span class="tech-tag">ECharts 5.6.0</span>
              <span class="tech-tag">Three.js</span>
              <span class="tech-tag">Vanta.js</span>
              <span class="tech-tag">Electron Store</span>
            </div>
          </div>
          
          <div class="about-section">
            <h4>🌟 关于 YNAA.NET</h4>
            <p><strong>YNAA</strong> 代表 "Your Next Awesome Application"，致力于为用户提供优质的开源应用程序。</p>
            <div class="team-philosophy">
              <h5>我们的理念</h5>
              <ul>
                <li>🆓 <strong>完全免费</strong>：所有应用永久免费使用</li>
                <li>🔓 <strong>开源透明</strong>：源代码完全开放，接受社区监督</li>
                <li>🚀 <strong>持续改进</strong>：根据用户反馈不断优化产品</li>
                <li>🤝 <strong>社区驱动</strong>：欢迎开发者参与贡献</li>
              </ul>
            </div>
            <div class="links">
              <a href="https://ynaa.net" target="_blank" class="link-btn">🌐 官方网站</a>
              <a href="https://gitee.com/wongvio/diandian-list" target="_blank" class="link-btn">📦 源码仓库</a>
              <a href="https://www.ynaa.net/topics/8" target="_blank" class="link-btn">📖 使用指南</a>
            </div>
          </div>
          
          <div class="about-section">
            <h4>📄 许可证</h4>
            <p>本项目采用 <strong>GNU Affero General Public License v3.0 (AGPL-3.0)</strong> 开源许可证。</p>
            <p class="license-note">如果您修改了本软件并通过网络提供服务，必须公开您的修改源代码。</p>
          </div>
        </div>
        <div class="modal-actions">
          <button @click="showAbout = false" class="btn-primary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useTodoStore } from '../stores/todoStore.js'
import { useSyncStore } from '../stores/syncStore.js'
import storageAPI from '@/api/storage'

const todoStore = useTodoStore()
const router = useRouter()
const versionManager = inject('versionManager')
const syncStore = useSyncStore()

// 同步相关的响应式数据
const autoSyncEnabled = ref(true)
const intervalSyncEnabled = ref(false)
const syncInterval = ref(15)
const lastSyncTime = computed(() => syncStore.formatSyncTime(syncStore.syncState.lastSyncTime))
const isSyncing = computed(() => syncStore.syncState.isSyncing)

// 响应式数据
const storagePath = ref('')
const storageType = ref('未知')
const exporting = ref(false)
const importing = ref(false)
const copied = ref(false)
const showClearConfirm = ref(false)
const showAbout = ref(false)
const selectedSound = ref('bell.mp3')
const isPlaying = ref(false)
const currentAudio = ref(null)
const selectedTheme = ref('default')

// 数据操作状态提示
const dataOperationMessage = ref('')
const dataOperationMessageType = ref('') // 'success', 'error', 'info'

// 导入确认模态框
const showImportConfirm = ref(false)
const importData_temp = ref(null) // 临时存储待导入的数据

// AI 模型配置
const aiConfig = ref({
  apiUrl: '',
  modelName: '',
  apiKey: ''
})
const showApiKey = ref(false)
const testingAi = ref(false)
const aiConfigStatus = ref('未配置')
const availableModels = ref([])
const loadingModels = ref(false)
const checkingBalance = ref(false)
const modelsError = ref(null) // 模型获取错误信息
const balanceInfo = ref({
  status: '',
  message: '',
  usage: null
})

// 版本管理
const currentVersion = ref('')
const latestVersion = ref('')
const hasNewVersion = ref(false)
const checkingVersion = ref(false)

// 主题配置
const themes = ref([
  {
    id: 'captain',
    name: '美国队长',
    description: '经典的红白蓝英雄配色',
    colors: ['#dc2626', '#1e3a8a', '#ffffff', '#1f2937']
  },
  {
    id: 'default',
    name: '浅色主题',
    description: '清新简洁的浅色主题',
    colors: ['#374151', '#ffffff', '#f8f9fa', '#1f2937']
  },
  {
    id: 'dark',
    name: '深色主题',
    description: '护眼舒适的深色主题',
    colors: ['#6b7280', '#1f2937', '#374151', '#f9fafb']
  },
  {
    id: 'zijinhong',
    name: '紫禁红',
    description: '中国传统紫禁红配色',
    colors: ['#983928', '#146654', '#faf0d6', '#2c1810']
  },
  {
    id: 'gaojigan',
    name: '高级感',
    description: '现代高级感橙黄配色',
    colors: ['#EB7A53', '#F7D44C', '#F6ECC9', '#2c2c2c']
  },
  {
    id: 'fugu',
    name: '复古感',
    description: '复古怀旧蓝绿配色',
    colors: ['#faf0d6', '#69929a', '#b9130a', '#2c1810']
  },
  {
    id: 'fenfen',
    name: '粉粉海报',
    description: '温柔粉色系配色',
    colors: ['#FEACB4', '#99AFE1', '#F6ECC9', '#4a0e4e']
  },
  {
    id: 'dongfang',
    name: '东方美学',
    description: '中式传统字体配色',
    colors: ['#12615E', '#E6C054', '#CCE3E4', '#1a3d0a']
  }
])

// 返回上一页
function goBack() {
  router.push('/todo')
}

// 同步相关方法
async function updateAutoSync() {
  try {
    await syncStore.setAutoSync(autoSyncEnabled.value)
    console.log('自动同步设置已更新:', autoSyncEnabled.value)
  } catch (error) {
    console.error('保存自动同步设置失败:', error)
  }
}

async function updateIntervalSync() {
  try {
    syncStore.syncState.intervalSyncEnabled = intervalSyncEnabled.value
    await storageAPI.setItem('intervalSyncEnabled', intervalSyncEnabled.value)
    
    if (intervalSyncEnabled.value) {
      syncStore.startIntervalSync()
    } else {
      syncStore.stopIntervalSync()
    }
    
    console.log('定时同步设置已更新:', intervalSyncEnabled.value)
  } catch (error) {
    console.error('保存定时同步设置失败:', error)
  }
}

async function updateSyncInterval() {
  try {
    syncStore.syncState.syncInterval = syncInterval.value
    await storageAPI.setItem('syncInterval', syncInterval.value)
    
    // 如果定时同步已启用，重新启动定时器
    if (intervalSyncEnabled.value) {
      syncStore.setIntervalSync(syncInterval.value)
    }
    
    console.log('同步间隔已更新:', syncInterval.value)
  } catch (error) {
    console.error('保存同步间隔设置失败:', error)
  }
}

async function handleSyncNow() {
  try {
    await syncStore.syncNow()
    console.log('手动同步完成')
  } catch (error) {
    console.error('手动同步失败:', error)
  }
}

// 初始化
onMounted(async () => {
  await loadStorageInfo()
  await loadSoundSettings()
  await loadThemeSettings()
  await loadAiConfig()
  await loadVersionInfo()
  await loadSyncSettings()
})

// 加载同步设置
async function loadSyncSettings() {
  try {
    const autoSync = await storageAPI.getItem('autoSyncEnabled', true)
    const intervalSync = await storageAPI.getItem('intervalSyncEnabled', false)
    const interval = await storageAPI.getItem('syncInterval', 15)
    
    autoSyncEnabled.value = autoSync
    intervalSyncEnabled.value = intervalSync
    syncInterval.value = interval
    
    // 同步到store
    syncStore.syncState.autoSyncEnabled = autoSync
    syncStore.syncState.intervalSyncEnabled = intervalSync
    syncStore.syncState.syncInterval = interval
    
    console.log('同步设置加载完成:', { autoSync, intervalSync, interval })
  } catch (error) {
    console.error('加载同步设置失败:', error)
  }
}

// 加载存储信息
async function loadStorageInfo() {
  try {
    if (todoStore.isElectron()) {
      storageType.value = 'Electron Store (本地文件)'
      const pathInfo = await todoStore.getStorePath()
      storagePath.value = pathInfo.path
    } else {
      storageType.value = 'LocalStorage (浏览器存储)'
      storagePath.value = ''
    }
  } catch (error) {
    console.error('获取存储信息失败:', error)
  }
}

// 复制路径
async function copyPath() {
  try {
    await navigator.clipboard.writeText(storagePath.value)
    copied.value = true
    setTimeout(() => {
      copied.value = false
    }, 2000)
  } catch (error) {
    console.error('复制失败:', error)
  }
}

// 显示数据操作消息
function showDataOperationMessage(message, type = 'info', duration = 4000) {
  dataOperationMessage.value = message
  dataOperationMessageType.value = type
  
  // 自动隐藏消息
  setTimeout(() => {
    dataOperationMessage.value = ''
    dataOperationMessageType.value = ''
  }, duration)
}

// 导出数据
async function exportData() {
  try {
    exporting.value = true
    
    // 获取当前所有数据
    const data = {
      lists: todoStore.state.lists,
      tasks: todoStore.state.tasks,
      exportTime: new Date().toISOString(),
      version: versionManager?.getCurrentVersion() || '1.0.0',
      appName: '点点清单'
    }
    
    const result = await storageAPI.exportData(data)
    
    if (result.success && !result.canceled) {
      const listCount = data.lists.length
      const taskCount = data.tasks.length
      showDataOperationMessage(
        `数据导出成功！已导出 ${listCount} 个清单和 ${taskCount} 个任务`,
        'success'
      )
    } else if (result.canceled) {
      showDataOperationMessage('已取消导出操作', 'info', 2000)
    } else {
      showDataOperationMessage('导出失败：未知错误', 'error')
    }
  } catch (error) {
    console.error('导出数据失败:', error)
    showDataOperationMessage(`导出失败：${error.message || '未知错误'}`, 'error')
  } finally {
    exporting.value = false
  }
}

// 导入数据
async function importData() {
  try {
    importing.value = true
    
    const result = await storageAPI.importData()
    
    if (result.success && result.data) {
      // 验证数据格式
      if (result.data.lists && result.data.tasks) {
        // 检查本地数据是否为空
        const hasLocalLists = todoStore.state.lists && todoStore.state.lists.length > 0
        const hasLocalTasks = todoStore.state.tasks && todoStore.state.tasks.length > 0
        const isLocalDataEmpty = !hasLocalLists && !hasLocalTasks
        
        // 如果本地数据为空，直接导入
        if (isLocalDataEmpty) {
          await directImport(result.data)
        } else {
          // 本地有数据，显示确认模态框
          importData_temp.value = result.data
          showImportConfirm.value = true
        }
      } else {
        console.error('数据格式错误：缺少必要的lists或tasks字段')
        showDataOperationMessage('数据格式错误，请选择正确的数据文件', 'error')
      }
    } else if (result.canceled) {
      showDataOperationMessage('已取消选择文件', 'info', 2000)
    } else {
      console.error('导入失败:', result.error)
      showDataOperationMessage(`导入失败：${result.error || '未知错误'}`, 'error')
    }
  } catch (error) {
    console.error('导入数据失败:', error)
    showDataOperationMessage(`导入失败：${error.message || '文件格式错误'}`, 'error')
  } finally {
    importing.value = false
  }
}

// 直接导入数据（用于本地数据为空的情况）
async function directImport(data) {
  try {
    // 直接导入数据
    todoStore.state.lists = data.lists
    todoStore.state.tasks = data.tasks
    
    // 保存到本地存储
    await todoStore.saveAllData()
    
    const listCount = data.lists.length
    const taskCount = data.tasks.length
    showDataOperationMessage(
      `数据导入成功！已导入 ${listCount} 个清单和 ${taskCount} 个任务`,
      'success'
    )
  } catch (error) {
    console.error('直接导入失败:', error)
    showDataOperationMessage(`导入失败：${error.message || '未知错误'}`, 'error')
  }
}

// 确认导入数据
async function confirmImport() {
  try {
    if (importData_temp.value) {
      // 合并导入数据，处理重复项
      const mergeResult = mergeImportData(importData_temp.value)
      
      // 更新数据
      todoStore.state.lists = mergeResult.lists
      todoStore.state.tasks = mergeResult.tasks
      
      // 保存到本地存储
      await todoStore.saveAllData()
      
      // 显示导入结果
      const { newLists, newTasks, updatedLists, updatedTasks } = mergeResult.stats
      let message = '数据导入成功！'
      if (newLists > 0 || newTasks > 0) {
        message += `新增 ${newLists} 个清单和 ${newTasks} 个任务`
      }
      if (updatedLists > 0 || updatedTasks > 0) {
        if (newLists > 0 || newTasks > 0) message += '，'
        message += `更新 ${updatedLists} 个清单和 ${updatedTasks} 个任务`
      }
      
      showDataOperationMessage(message, 'success')
      
      // 清理临时数据并关闭模态框
      importData_temp.value = null
      showImportConfirm.value = false
    }
  } catch (error) {
    console.error('确认导入失败:', error)
    showDataOperationMessage(`导入失败：${error.message || '未知错误'}`, 'error')
    // 清理临时数据并关闭模态框
    importData_temp.value = null
    showImportConfirm.value = false
  }
}

// 合并导入数据，处理重复项
function mergeImportData(importData) {
  const currentLists = [...(todoStore.state.lists || [])]
  const currentTasks = [...(todoStore.state.tasks || [])]
  
  let newLists = 0, newTasks = 0, updatedLists = 0, updatedTasks = 0
  
  // 处理清单数据
  const existingListIds = new Set(currentLists.map(list => list.id))
  const existingListNames = new Set(currentLists.map(list => list.name))
  
  importData.lists.forEach(importList => {
    const existingListIndex = currentLists.findIndex(list => list.id === importList.id)
    
    if (existingListIndex >= 0) {
      // 更新现有清单
      currentLists[existingListIndex] = { ...importList }
      updatedLists++
    } else if (existingListNames.has(importList.name)) {
      // 同名清单，生成新ID
      const newList = { ...importList, id: Date.now() + Math.random() }
      currentLists.push(newList)
      newLists++
    } else {
      // 新清单
      currentLists.push(importList)
      newLists++
    }
  })
  
  // 处理任务数据
  const existingTaskIds = new Set(currentTasks.map(task => task.id))
  
  importData.tasks.forEach(importTask => {
    const existingTaskIndex = currentTasks.findIndex(task => task.id === importTask.id)
    
    if (existingTaskIndex >= 0) {
      // 更新现有任务
      currentTasks[existingTaskIndex] = { ...importTask }
      updatedTasks++
    } else {
      // 新任务
      currentTasks.push(importTask)
      newTasks++
    }
  })
  
  return {
    lists: currentLists,
    tasks: currentTasks,
    stats: { newLists, newTasks, updatedLists, updatedTasks }
  }
}

// 取消导入数据
function cancelImport() {
  importData_temp.value = null
  showImportConfirm.value = false
  showDataOperationMessage('已取消数据导入', 'info', 2000)
}

// 清空所有数据
async function clearAllData() {
  try {
    await todoStore.clearAllData()
    showClearConfirm.value = false
    console.log('数据清空成功')
  } catch (error) {
    console.error('清空数据失败:', error)
  }
}

// 加载提示音设置
async function loadSoundSettings() {
  try {
    const settings = await storageAPI.getItem('pomodoroSettings', {})
    const settingsObj = typeof settings === 'string' ? JSON.parse(settings) : (settings || {})
    selectedSound.value = settingsObj.completionSound || 'bell.mp3'
  } catch (error) {
    console.warn('加载提示音设置失败:', error)
    selectedSound.value = 'bell.mp3'
  }
}

// 保存提示音设置
async function saveSoundSettings() {
  try {
    const settings = await storageAPI.getItem('pomodoroSettings', {})
    const settingsObj = typeof settings === 'string' ? JSON.parse(settings) : (settings || {})
    settingsObj.completionSound = selectedSound.value
    await storageAPI.setItem('pomodoroSettings', JSON.stringify(settingsObj))
  } catch (error) {
    console.error('保存提示音设置失败:', error)
  }
}

// 提示音改变时的处理
async function onSoundChange() {
  await saveSoundSettings()
  // 停止当前播放的音频
  if (currentAudio.value) {
    currentAudio.value.pause()
    currentAudio.value = null
    isPlaying.value = false
  }
}

// 试听提示音
async function previewSound() {
  if (isPlaying.value) {
    // 停止播放
    if (currentAudio.value) {
      currentAudio.value.pause()
      currentAudio.value = null
    }
    isPlaying.value = false
  } else {
    // 开始播放
    try {
      // 使用Electron API获取正确的资源路径
      const audioPath = window.electronAPI ? 
        await window.electronAPI.getResourcePath(`bell/${selectedSound.value}`) : 
        `/bell/${selectedSound.value}`
      currentAudio.value = new Audio(audioPath)
      currentAudio.value.volume = 0.5
      
      currentAudio.value.onended = () => {
        isPlaying.value = false
        currentAudio.value = null
      }
      
      currentAudio.value.onerror = () => {
        console.error('音频加载失败:', audioPath)
        isPlaying.value = false
        currentAudio.value = null
      }
      
      currentAudio.value.play()
      isPlaying.value = true
    } catch (error) {
      console.error('播放音频失败:', error)
      isPlaying.value = false
    }
  }
}

// 加载主题设置
async function loadThemeSettings() {
  try {
    const savedTheme = await storageAPI.getItem('app-theme') || 'captain'
    selectedTheme.value = savedTheme
    applyTheme(savedTheme)
  } catch (error) {
    console.warn('加载主题设置失败:', error)
    selectedTheme.value = 'captain'
    applyTheme('captain')
  }
}

// 保存主题设置
async function saveTheme(themeId) {
  try {
    await storageAPI.setItem('app-theme', themeId)
  } catch (error) {
    console.error('保存主题设置失败:', error)
  }
}

// 加载AI配置
async function loadAiConfig() {
  try {
    const config = await storageAPI.getItem('aiModelConfig', {})
    
    // 确保config是对象类型
    const configObj = typeof config === 'string' ? JSON.parse(config) : (config || {})
    
    // 只有当配置存在且有效时才更新
    if (configObj && typeof configObj === 'object') {
      aiConfig.value = {
        apiUrl: (configObj.apiUrl || aiConfig.value.apiUrl || 'https://ark.cn-beijing.volces.com/api/v3/chat/completions').trim().replace(/[`]/g, ''),
        modelName: (configObj.modelName || aiConfig.value.modelName || 'doubao-seed-1-6-flash-250615').trim(),
        apiKey: (configObj.apiKey || aiConfig.value.apiKey || '').trim()
      }
    } else {
      // 如果没有保存的配置，使用默认值但不覆盖现有值
      aiConfig.value = {
        apiUrl: (aiConfig.value.apiUrl || 'https://ark.cn-beijing.volces.com/api/v3/chat/completions').trim().replace(/[`]/g, ''),
        modelName: (aiConfig.value.modelName || 'doubao-seed-1-6-flash-250615').trim(),
        apiKey: (aiConfig.value.apiKey || '').trim()
      }
    }
    updateAiConfigStatus()
    console.log('AI配置加载成功:', aiConfig.value)
    
    // 如果配置完整，自动加载模型列表
    if (aiConfig.value.apiUrl && aiConfig.value.apiKey) {
      await refreshModels()
    }
  } catch (error) {
    console.warn('加载AI配置失败:', error)
    // 发生错误时不要覆盖现有配置，只更新状态
    aiConfigStatus.value = '加载失败'
    updateAiConfigStatus()
  }
}

// 保存AI配置
async function saveAiConfig() {
  try {
    // 清理配置数据，移除反引号和多余空格
    const cleanConfig = {
      apiUrl: (aiConfig.value.apiUrl || '').trim().replace(/[`]/g, ''),
      modelName: (aiConfig.value.modelName || '').trim(),
      apiKey: (aiConfig.value.apiKey || '').trim()
    }
    
    console.log('正在保存AI配置:', cleanConfig)
    const result = await storageAPI.setItem('aiModelConfig', cleanConfig)
    console.log('保存结果:', result)
    
    // 更新本地配置为清理后的数据
    aiConfig.value = cleanConfig
    
    // 验证保存是否成功
    const savedConfig = await storageAPI.getItem('aiModelConfig', {})
    console.log('验证保存的配置:', savedConfig)
    
    updateAiConfigStatus()
    console.log('AI配置保存成功')
  } catch (error) {
    console.error('保存AI配置失败:', error)
    aiConfigStatus.value = '保存失败'
  }
}

// 更新AI配置状态
function updateAiConfigStatus() {
  const { apiUrl, modelName, apiKey } = aiConfig.value
  if (!apiUrl || !modelName || !apiKey) {
    aiConfigStatus.value = '配置不完整'
  } else {
    aiConfigStatus.value = '配置完整'
  }
}

// 测试AI配置
async function testAiConfig() {
  if (!aiConfig.value.apiUrl || !aiConfig.value.modelName || !aiConfig.value.apiKey) {
    aiConfigStatus.value = '请先完成配置'
    return
  }

  testingAi.value = true
  try {
    const response = await fetch(aiConfig.value.apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${aiConfig.value.apiKey}`
      },
      body: JSON.stringify({
        model: aiConfig.value.modelName,
        messages: [{
          role: 'user',
          content: '测试连接'
        }],
        max_tokens: 10
      })
    })

    if (response.ok) {
      aiConfigStatus.value = '连接成功'
    } else {
      const errorData = await response.text()
      aiConfigStatus.value = `连接失败: ${response.status}`
      console.error('API测试失败:', errorData)
    }
  } catch (error) {
    aiConfigStatus.value = `连接错误: ${error.message}`
    console.error('测试AI配置失败:', error)
  } finally {
    testingAi.value = false
  }
}

// 刷新模型列表
async function refreshModels() {
  if (!aiConfig.value.apiUrl || !aiConfig.value.apiKey) {
    console.warn('请先配置API URL和API Key')
    return
  }

  loadingModels.value = true
  modelsError.value = null // 清除之前的错误
  try {
    // 动态导入aiConfig模块
    const { getAvailableModels } = await import('@/utils/aiConfig')
    const result = await getAvailableModels(aiConfig.value)
    
    if (result.success) {
      availableModels.value = result.models
      console.log('模型列表加载成功:', result.models)
    } else {
      availableModels.value = result.models || []
      console.error('获取模型列表失败:', result.message)
      
      // 设置错误信息
      modelsError.value = {
        message: result.message,
        faqUrl: result.faqUrl,
        error: result.error
      }
    }
  } catch (error) {
    console.error('获取模型列表失败:', error)
    availableModels.value = []
    modelsError.value = {
      message: `网络错误: ${error.message}`,
      error: error.message
    }
  } finally {
    loadingModels.value = false
  }
}

// 查询账户余额
async function checkBalance() {
  if (!aiConfig.value.apiUrl || !aiConfig.value.modelName || !aiConfig.value.apiKey) {
    balanceInfo.value = {
      status: 'error',
      message: '请先完成配置',
      usage: null
    }
    return
  }

  checkingBalance.value = true
  try {
    // 动态导入aiConfig模块
    const { getAccountBalance } = await import('@/utils/aiConfig')
    const balance = await getAccountBalance(aiConfig.value)
    
    // 如果是404错误，添加FAQ链接信息
    if (balance.faqUrl) {
      balance.message = `${balance.message}，问题解决方式请点击：${balance.faqUrl}`
    }
    
    balanceInfo.value = balance
    console.log('余额查询结果:', balance)
  } catch (error) {
    console.error('查询余额失败:', error)
    balanceInfo.value = {
      status: 'error',
      message: `查询失败: ${error.message}`,
      usage: null
    }
  } finally {
    checkingBalance.value = false
  }
}

// 格式化消息中的链接
function formatMessageWithLink(message, faqUrl) {
  if (!message || !faqUrl) return message
  
  // 将FAQ URL替换为可点击的链接
  return message.replace(faqUrl, `<a href="${faqUrl}" target="_blank" style="color: var(--primary-color, #3b82f6); text-decoration: underline;">${faqUrl}</a>`)
}

// 应用主题
function applyTheme(themeId) {
  const theme = themes.value.find(t => t.id === themeId)
  if (!theme) return
  
  const root = document.documentElement
  
  // 根据主题设置CSS变量
  switch (themeId) {
    case 'default':
      root.style.setProperty('--primary-color', '#374151')
      root.style.setProperty('--primary-hover', '#1f2937')
      root.style.setProperty('--background-color', '#ffffff')
      root.style.setProperty('--surface-color', '#f9fafb')
      root.style.setProperty('--title-color', '#1f2937')
      root.style.setProperty('--text-primary', '#111827')
      root.style.setProperty('--text-secondary', '#4b5563')
      root.style.setProperty('--border-color', '#e5e7eb')
      root.style.setProperty('--shadow-color', 'rgba(0, 0, 0, 0.05)')
      root.style.setProperty('--button-secondary-bg', '#f3f4f6')
      root.style.setProperty('--button-secondary-hover', '#e5e7eb')
      root.style.setProperty('--modal-bg', '#ffffff')
      root.style.setProperty('--modal-overlay', 'rgba(0, 0, 0, 0.5)')
      break
    case 'dark':
      root.style.setProperty('--primary-color', '#6b7280')
      root.style.setProperty('--primary-hover', '#4b5563')
      root.style.setProperty('--background-color', '#1f2937')
      root.style.setProperty('--surface-color', '#374151')
      root.style.setProperty('--title-color', '#ffffff')
      root.style.setProperty('--text-primary', '#f9fafb')
      root.style.setProperty('--text-secondary', '#d1d5db')
      root.style.setProperty('--border-color', '#4b5563')
      root.style.setProperty('--shadow-color', 'rgba(0, 0, 0, 0.3)')
      root.style.setProperty('--button-secondary-bg', '#374151')
      root.style.setProperty('--button-secondary-hover', '#4b5563')
      root.style.setProperty('--modal-bg', '#374151')
      root.style.setProperty('--modal-overlay', 'rgba(0, 0, 0, 0.7)')
      break
    case 'captain':
      root.style.setProperty('--primary-color', '#dc2626')
      root.style.setProperty('--primary-hover', '#b91c1c')
      root.style.setProperty('--background-color', '#ffffff')
      root.style.setProperty('--surface-color', '#f8fafc')
      root.style.setProperty('--title-color', '#ffffff')
      root.style.setProperty('--text-primary', '#1e3a8a')
      root.style.setProperty('--text-secondary', '#475569')
      root.style.setProperty('--border-color', '#e2e8f0')
      root.style.setProperty('--shadow-color', 'rgba(30, 58, 138, 0.1)')
      root.style.setProperty('--button-secondary-bg', '#f1f5f9')
      root.style.setProperty('--button-secondary-hover', '#e2e8f0')
      root.style.setProperty('--modal-bg', '#ffffff')
      root.style.setProperty('--modal-overlay', 'rgba(220, 38, 38, 0.2)')
      break
    case 'zijinhong':
      root.style.setProperty('--primary-color', '#983928')
      root.style.setProperty('--primary-hover', '#7a2d20')
      root.style.setProperty('--background-color', '#faf0d6')
      root.style.setProperty('--surface-color', '#f5e8c8')
      root.style.setProperty('--title-color', '#2c1810')
      root.style.setProperty('--text-primary', '#2c1810')
      root.style.setProperty('--text-secondary', '#146654')
      root.style.setProperty('--border-color', '#e8d4a0')
      root.style.setProperty('--shadow-color', 'rgba(152, 57, 40, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#f5e8c8')
      root.style.setProperty('--button-secondary-hover', '#e8d4a0')
      root.style.setProperty('--modal-bg', '#faf0d6')
      root.style.setProperty('--modal-overlay', 'rgba(152, 57, 40, 0.2)')
      break
    case 'gaojigan':
      root.style.setProperty('--primary-color', '#EB7A53')
      root.style.setProperty('--primary-hover', '#d96942')
      root.style.setProperty('--background-color', '#fefcf8')
      root.style.setProperty('--surface-color', '#fdf9f2')
      root.style.setProperty('--title-color', '#8B4513')
      root.style.setProperty('--text-primary', '#8B4513')
      root.style.setProperty('--text-secondary', '#D2691E')
      root.style.setProperty('--border-color', '#f5e6d8')
      root.style.setProperty('--shadow-color', 'rgba(235, 122, 83, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#fdf9f2')
      root.style.setProperty('--button-secondary-hover', '#f5e6d8')
      root.style.setProperty('--modal-bg', '#fefcf8')
      root.style.setProperty('--modal-overlay', 'rgba(235, 122, 83, 0.2)')
      break
    case 'fugu':
      root.style.setProperty('--primary-color', '#69929a')
      root.style.setProperty('--primary-hover', '#5a7d84')
      root.style.setProperty('--background-color', '#f8fafa')
      root.style.setProperty('--surface-color', '#f1f5f5')
      root.style.setProperty('--title-color', '#2F4F4F')
      root.style.setProperty('--text-primary', '#2F4F4F')
      root.style.setProperty('--text-secondary', '#8B0000')
      root.style.setProperty('--border-color', '#d9e5e6')
      root.style.setProperty('--shadow-color', 'rgba(105, 146, 154, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#f1f5f5')
      root.style.setProperty('--button-secondary-hover', '#d9e5e6')
      root.style.setProperty('--modal-bg', '#f8fafa')
      root.style.setProperty('--modal-overlay', 'rgba(105, 146, 154, 0.2)')
      break
    case 'fenfen':
      root.style.setProperty('--primary-color', '#FEACB4')
      root.style.setProperty('--primary-hover', '#fe9aa4')
      root.style.setProperty('--background-color', '#fffcfd')
      root.style.setProperty('--surface-color', '#fef8f9')
      root.style.setProperty('--title-color', '#8B008B')
      root.style.setProperty('--text-primary', '#8B008B')
      root.style.setProperty('--text-secondary', '#4169E1')
      root.style.setProperty('--border-color', '#f9e6e9')
      root.style.setProperty('--shadow-color', 'rgba(254, 172, 180, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#fef8f9')
      root.style.setProperty('--button-secondary-hover', '#f9e6e9')
      root.style.setProperty('--modal-bg', '#fffcfd')
      root.style.setProperty('--modal-overlay', 'rgba(254, 172, 180, 0.2)')
      break
    case 'dongfang':
      root.style.setProperty('--primary-color', '#12615E')
      root.style.setProperty('--primary-hover', '#0e4e4c')
      root.style.setProperty('--background-color', '#f6f9f9')
      root.style.setProperty('--surface-color', '#eef5f4')
      root.style.setProperty('--title-color', '#2F4F4F')
      root.style.setProperty('--text-primary', '#2F4F4F')
      root.style.setProperty('--text-secondary', '#B8860B')
      root.style.setProperty('--border-color', '#c7d9d8')
      root.style.setProperty('--shadow-color', 'rgba(18, 97, 94, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#eef5f4')
      root.style.setProperty('--button-secondary-hover', '#c7d9d8')
      root.style.setProperty('--modal-bg', '#f6f9f9')
      root.style.setProperty('--modal-overlay', 'rgba(18, 97, 94, 0.2)')
      break
  }
  
  // 更新番茄钟主题
  updatePomodoroTheme(themeId)
}

// 更新番茄钟主题
function updatePomodoroTheme(themeId) {
  const root = document.documentElement
  
  switch (themeId) {
    case 'default':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #f8f9fa 0%, #e5e7eb 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%)')
      break
    case 'dark':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #374151 0%, #1f2937 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #4b5563 0%, #374151 100%)')
      break
    case 'captain':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%)')
      break
    case 'zijinhong':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #983928 0%, #7a2d20 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #146654 0%, #0f4d3f 100%)')
      break
    case 'gaojigan':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #EB7A53 0%, #d96942 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #F7D44C 0%, #e6c43b 100%)')
      break
    case 'fugu':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #69929a 0%, #5a7d84 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #b9130a 0%, #9a0f08 100%)')
      break
    case 'fenfen':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #FEACB4 0%, #fe9aa4 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #99AFE1 0%, #7a9bd8 100%)')
      break
    case 'dongfang':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #12615E 0%, #0e4e4c 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #E6C054 0%, #d4ae43 100%)')
      break
  }
}

// 选择主题
async function selectTheme(themeId) {
  if (selectedTheme.value === themeId) return
  
  selectedTheme.value = themeId
  await saveTheme(themeId)
  applyTheme(themeId)
  
  // 添加视觉反馈
  const themeOption = document.querySelector(`[data-theme-id="${themeId}"]`)
  if (themeOption) {
    themeOption.style.transform = 'scale(0.95)'
    setTimeout(() => {
      themeOption.style.transform = ''
    }, 150)
  }
  
  console.log(`主题已切换到: ${themes.value.find(t => t.id === themeId)?.name}`)
}

// 加载版本信息
async function loadVersionInfo() {
  try {
    if (versionManager) {
      currentVersion.value = versionManager.getCurrentVersion()
      await checkVersion()
    }
  } catch (error) {
    console.error('加载版本信息失败:', error)
  }
}

// 检查版本更新
async function checkVersion() {
  try {
    checkingVersion.value = true
    
    if (versionManager) {
      const result = await versionManager.checkForUpdates()
      latestVersion.value = result.latestVersion
      hasNewVersion.value = result.hasUpdate
    }
  } catch (error) {
    console.error('检查版本更新失败:', error)
    latestVersion.value = '检查失败'
    hasNewVersion.value = false
  } finally {
    checkingVersion.value = false
  }
}

// 打开升级页面
function openUpgradePage() {
  if (versionManager) {
    versionManager.openUpgradePage()
  }
}
</script>

<style scoped>
.settings-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: var(--surface-color, #f9fafb);
  min-height: 100vh;
  max-height: 100vh;
  overflow-y: auto;
}

/* 数据操作状态提示样式 */
.data-operation-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  margin-bottom: 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  border: 1px solid;
  animation: slideIn 0.3s ease-out;
}

.data-operation-message.success {
  background-color: #f0f9ff;
  border-color: #22c55e;
  color: #16a34a;
}

.data-operation-message.error {
  background-color: #fef2f2;
  border-color: #ef4444;
  color: #dc2626;
}

.data-operation-message.info {
  background-color: #f0f9ff;
  border-color: #3b82f6;
  color: #2563eb;
}

.data-operation-message svg {
  flex-shrink: 0;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 深色主题下的状态提示样式 */
[data-theme="dark"] .data-operation-message.success {
  background-color: rgba(34, 197, 94, 0.1);
  border-color: #22c55e;
  color: #4ade80;
}

[data-theme="dark"] .data-operation-message.error {
  background-color: rgba(239, 68, 68, 0.1);
  border-color: #ef4444;
  color: #f87171;
}

[data-theme="dark"] .data-operation-message.info {
  background-color: rgba(59, 130, 246, 0.1);
  border-color: #3b82f6;
  color: #60a5fa;
}

/* 导入确认模态框样式 */
.import-info {
  margin: 16px 0;
}

.import-info p {
  margin: 0 0 12px 0;
  color: var(--text-primary);
  font-weight: 500;
}

.import-details {
  background: var(--surface-color, #f8f9fa);
  border-radius: 8px;
  padding: 12px;
  margin: 12px 0;
  border: 1px solid var(--border-color, #e5e7eb);
}

.import-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0;
  color: var(--text-primary);
  font-size: 14px;
}

.import-item svg {
  color: var(--primary-color);
  flex-shrink: 0;
}

.import-warning {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: 6px;
  padding: 10px;
  margin-top: 12px;
  color: #dc2626;
  font-weight: 500;
  font-size: 14px;
}

.import-warning svg {
  color: #dc2626;
  flex-shrink: 0;
}

/* 深色主题下的导入确认样式 */
[data-theme="dark"] .import-details {
  background: var(--surface-color, #374151);
  border-color: var(--border-color, #4b5563);
}

[data-theme="dark"] .import-warning {
  background: rgba(239, 68, 68, 0.15);
  border-color: rgba(239, 68, 68, 0.3);
  color: #fca5a5;
}

[data-theme="dark"] .import-warning svg {
  color: #fca5a5;
}

.settings-header {
  position: relative;
  text-align: center;
  margin-bottom: 40px;
}

.back-button {
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  background: var(--button-secondary-bg, #f3f4f6);
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 14px;
  color: var(--text-primary, #374151);
  cursor: pointer;
  transition: all 0.2s;
}

.back-button:hover {
  background: var(--button-secondary-hover, #e5e7eb);
  transform: translateX(-2px);
}

.back-button svg {
  transition: transform 0.2s;
}

.back-button:hover svg {
  transform: translateX(-2px);
}

.settings-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary, #1f2937);
  margin-bottom: 8px;
}

.settings-header p {
  color: var(--text-secondary, #6b7280);
  font-size: 16px;
}

.setting-section {
  background: var(--background-color, white);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px var(--shadow-color, rgba(0, 0, 0, 0.1));
}

.setting-section h2 {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary, #1f2937);
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 5px;
  padding: 16px 0;
  border-bottom: 1px solid var(--border-color, #f3f4f6);
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-item.danger {
  border-left: 4px solid #ef4444;
  padding-left: 16px;
  margin-left: -20px;
}

.setting-info h3 {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary, #1f2937);
  margin-bottom: 4px;
}

.setting-info p {
  color: var(--text-secondary, #6b7280);
  font-size: 14px;
  margin: 0;
}

.path-text {
  font-family: 'Courier New', monospace;
  background: var(--button-secondary-bg, #f3f4f6);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  word-break: break-all;
}

.btn-primary {
  background: var(--primary-color, #3b82f6);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-primary:hover:not(:disabled) {
  background: var(--primary-hover, #2563eb);
}

.btn-primary:disabled {
  background: var(--text-secondary, #9ca3af);
  cursor: not-allowed;
}

.btn-secondary {
  background: var(--button-secondary-bg);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-secondary:hover:not(:disabled) {
  background: var(--button-secondary-hover, #e5e7eb);
}

.btn-danger {
  background: #ef4444;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-danger:hover {
  background: #dc2626;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: var(--modal-bg, white);
  border-radius: 12px;
  padding: 24px;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 10px 25px var(--shadow-color, rgba(0, 0, 0, 0.2));
}

.modal h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary, #1f2937);
  margin-bottom: 12px;
}

.modal p {
  color: var(--text-secondary, #6b7280);
  margin-bottom: 20px;
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.modal-actions .btn-danger:hover {
  background: #dc2626;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

/* 提示音选择器样式 */
.sound-selector {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sound-select {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 6px;
  background: var(--background-color, white);
  font-size: 14px;
  color: var(--text-primary, #374151);
  cursor: pointer;
  transition: border-color 0.2s;
}

.sound-select:focus {
  outline: none;
  border-color: var(--primary-color, #3b82f6);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.preview-btn {
  min-width: 60px;
  white-space: nowrap;
}

/* 关于我们对话框样式 */
.about-modal {
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
}

.about-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

.about-header h3 {
  margin: 0;
  color: var(--text-primary, #1f2937);
  font-size: 20px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-secondary, #6b7280);
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: var(--button-secondary-bg, #f3f4f6);
  color: var(--text-primary, #374151);
}

.about-content {
  margin-bottom: 20px;
}

.about-section {
  margin-bottom: 24px;
}

.about-section h4 {
  margin: 0 0 12px 0;
  color: var(--text-primary, #1f2937);
  font-size: 16px;
  font-weight: 600;
}

.about-section h5 {
  color: var(--text-primary, #1f2937);
  margin: 12px 0 8px 0;
  font-size: 14px;
  font-weight: 600;
}

.about-section p {
  margin: 0 0 8px 0;
  color: var(--text-secondary, #4b5563);
  line-height: 1.6;
}

.about-section ul {
  margin: 0;
  padding-left: 20px;
  color: var(--text-secondary, #4b5563);
}

.about-section li {
  margin-bottom: 6px;
  line-height: 1.5;
}

.about-section a {
  color: var(--primary-color, #3b82f6);
  text-decoration: none;
}

.about-section a:hover {
  text-decoration: underline;
}

.warning-notice {
  background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
  border: 1px solid #ffc107;
  border-radius: 8px;
  padding: 16px;
  margin: 16px 0;
}

.warning-notice h5 {
  color: #856404;
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
}

.warning-notice p {
  color: #856404;
  margin: 0;
  font-size: 13px;
  line-height: 1.5;
}

.warning-notice strong {
  color: #dc3545;
  font-weight: 600;
}

.team-philosophy {
  background: var(--surface-color, #f8f9fa);
  border: 1px solid var(--border-color, #e5e7eb);
  border-radius: 8px;
  padding: 16px;
  margin: 16px 0;
}

.team-philosophy h5 {
  margin-top: 0;
}

.team-philosophy ul {
  margin: 8px 0 0 0;
  padding-left: 16px;
}

.team-philosophy li {
  margin-bottom: 8px;
  font-size: 14px;
}

.tech-stack {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.tech-tag {
  background: var(--surface-color, #eff6ff);
  color: var(--primary-color, #1d4ed8);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.links {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

.link-btn {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  background: var(--button-secondary-bg, #f3f4f6);
  color: var(--text-primary, #374151);
  text-decoration: none;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s;
}

.link-btn:hover {
  background: var(--button-secondary-hover, #e5e7eb);
  transform: translateY(-1px);
}

.license-note {
  font-size: 13px;
  color: var(--text-secondary, #6b7280);
  font-style: italic;
}

/* 升级按钮样式 */
.upgrade-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  position: relative;
  overflow: hidden;
}

.upgrade-arrow {
  animation: bounce-up 2s ease-in-out infinite;
  transition: animation-duration 0.3s ease;
}

.upgrade-btn:hover .upgrade-arrow {
  animation-duration: 0.8s;
}

@keyframes bounce-up {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-4px);
  }
  60% {
    transform: translateY(-2px);
  }
}

/* 版本信息样式 */
.version-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.new-version-badge {
  display: inline-block;
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin-left: 8px;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.05);
  }
}

/* 主题选择器样式 */
.theme-selector {
  margin-top: 16px;
}

.theme-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 16px;
  margin-top: 12px;
}

.theme-option {
  cursor: pointer;
  border-radius: 12px;
  padding: 16px;
  border: 2px solid transparent;
  background: var(--surface-color, #f8f9fa);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.theme-option:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px var(--shadow-color, rgba(0, 0, 0, 0.1));
  border-color: var(--border-color, #e5e7eb);
}

.theme-option.active {
  border-color: var(--primary-color, #6366f1);
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.05) 0%, rgba(99, 102, 241, 0.02) 100%);
  box-shadow: 0 8px 25px rgba(99, 102, 241, 0.15);
}

.theme-option.active::before {
  content: '✓';
  position: absolute;
  top: 8px;
  right: 8px;
  width: 20px;
  height: 20px;
  background: var(--primary-color, #6366f1);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.theme-preview {
  text-align: center;
}

.theme-colors {
  display: flex;
  justify-content: center;
  gap: 4px;
  margin-bottom: 12px;
  padding: 8px;
  background: var(--background-color, white);
  border-radius: 8px;
  box-shadow: 0 2px 8px var(--shadow-color, rgba(0, 0, 0, 0.05));
}

.theme-color {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #cccccc;
  box-shadow: 0 2px 4px var(--shadow-color, rgba(0, 0, 0, 0.1));
  transition: transform 0.2s ease;
}

.theme-option:hover .theme-color {
  transform: scale(1.1);
}

.theme-info {
  text-align: center;
}

.theme-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary, #374151);
  margin: 0 0 4px 0;
  transition: color 0.2s ease;
}

.theme-description {
  font-size: 12px;
  color: var(--text-secondary, #6b7280);
  margin: 0;
  line-height: 1.3;
  transition: color 0.2s ease;
}

.theme-option.active .theme-name {
  color: var(--primary-color, #6366f1);
  font-weight: 600;
}

.theme-option.active .theme-description {
  color: var(--primary-color, #6366f1);
  opacity: 0.8;
}

.ai-config-input {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.config-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--background-color);
  color: var(--text-primary);
  font-size: 14px;
  transition: all 0.2s ease;
}

/* AI配置相关样式 */
.model-select {
  flex: 1;
  margin-right: 8px;
}

.refresh-btn {
  padding: 8px;
  min-width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.refresh-btn:hover:not(:disabled) {
  background-color: var(--secondary-hover, #f1f5f9);
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.rotating {
  animation: spin 1s linear infinite;
}

.config-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.balance-info {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  background-color: var(--background-secondary, #f8f9fa);
  border-left: 3px solid var(--border-color, #e2e8f0);
}

.balance-status {
  margin: 0;
  font-size: 14px;
  color: var(--text-primary, #374151);
}

.balance-info.success {
  border-left-color: var(--success-color, #10b981);
}

.balance-info.error {
  border-left-color: var(--error-color, #ef4444);
}

.balance-info.warning {
  border-left-color: var(--warning-color, #f59e0b);
}

.balance-status.success {
  color: var(--success-color, #10b981);
}

.balance-status.error {
  color: var(--error-color, #ef4444);
}

.balance-status.warning {
  color: var(--warning-color, #f59e0b);
}

.usage-info {
  margin-top: 4px;
}

.usage-info small {
  color: var(--text-secondary, #6b7280);
  font-size: 12px;
}

.ai-config-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-info {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  background-color: #fef2f2;
  border-left: 3px solid var(--error-color, #ef4444);
}

.error-message {
  margin: 0;
  font-size: 14px;
  color: var(--error-color, #ef4444);
}

.error-message a {
  color: var(--primary-color, #3b82f6);
  text-decoration: underline;
}

.error-message a:hover {
  text-decoration: none;
}

.config-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb), 0.1);
}

.config-input::placeholder {
  color: var(--text-secondary);
}

.toggle-btn {
  padding: 8px;
  min-width: auto;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toggle-btn svg {
  width: 16px;
  height: 16px;
}

.config-description {
  margin-bottom: 16px;
  padding: 12px 16px;
  background: var(--surface-color, #f8fafc);
  border: 1px solid var(--border-color, #e2e8f0);
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
  color: var(--text-secondary, #64748b);
}

.config-link {
  color: var(--primary-color, #6366f1);
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s ease;
}

.config-link:hover {
  color: var(--primary-color-hover, #4f46e5);
  text-decoration: underline;
}

[data-theme="dark"] .config-description {
  background: var(--surface-color, #374151);
  border-color: var(--border-color, #4b5563);
  color: var(--text-secondary, #9ca3af);
}

.theme-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 16px;
  padding: 12px 16px;
  background: var(--surface-color, linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%));
  border: 1px solid var(--border-color, #bae6fd);
  border-radius: 8px;
  color: var(--text-secondary, #0369a1);
  font-size: 13px;
  line-height: 1.4;
}

.theme-tip svg {
  flex-shrink: 0;
  opacity: 0.7;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .theme-options {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .theme-option {
    padding: 12px;
  }
  
  .theme-colors {
    gap: 3px;
    margin-bottom: 8px;
  }
  
  .theme-color {
    width: 16px;
    height: 16px;
  }
  
  .theme-name {
    font-size: 13px;
    margin-bottom: 2px;
  }
  
  .theme-description {
    font-size: 11px;
    line-height: 1.2;
  }
  
  .theme-tip {
    padding: 10px 12px;
    font-size: 12px;
  }
  
  .theme-tip svg {
    width: 14px;
    height: 14px;
  }
}

/* 主题切换动画 */
* {
  transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}

/* 深色主题下的特殊样式 */
[data-theme="dark"] .theme-option {
  background: var(--surface-color, #374151);
  border-color: var(--border-color, #4b5563);
}

[data-theme="dark"] .theme-option:hover {
  border-color: var(--text-secondary, #6b7280);
}

[data-theme="dark"] .theme-colors {
  background: var(--background-color, #1f2937);
}

[data-theme="dark"] .theme-name {
  color: var(--text-primary, #d1d5db);
}

/* 同步相关样式 */
.sync-status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: var(--success-color-light, #f0f9ff);
  border: 1px solid var(--success-color, #10b981);
  border-radius: 6px;
  color: var(--success-color, #10b981);
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.sync-status-indicator.syncing {
  background: var(--warning-color-light, #fef3c7);
  border-color: var(--warning-color, #f59e0b);
  color: var(--warning-color, #f59e0b);
}

.sync-status-indicator svg {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
}

.sync-status-indicator .spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.sync-time-info {
  font-size: 12px;
  color: var(--text-secondary, #6b7280);
  margin-top: 4px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--border-color, #e2e8f0);
  transition: 0.3s;
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: 0.3s;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

input:checked + .slider {
  background-color: var(--primary-color, #6366f1);
}

input:checked + .slider:before {
  transform: translateX(20px);
}

.interval-select {
  padding: 8px 12px;
  border: 1px solid var(--border-color, #e2e8f0);
  border-radius: 6px;
  background: var(--background-color, #ffffff);
  color: var(--text-primary, #374151);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 120px;
}

.interval-select:focus {
  outline: none;
  border-color: var(--primary-color, #6366f1);
  box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb, 99, 102, 241), 0.1);
}

.sync-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  background: var(--primary-color, #6366f1);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 120px;
  justify-content: center;
}

.sync-btn:hover:not(:disabled) {
  background: var(--primary-color-hover, #4f46e5);
  transform: translateY(-1px);
}

.sync-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.sync-btn svg {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
}

.sync-btn .spinning {
  animation: spin 1s linear infinite;
}

/* 深色主题下的同步样式 */
[data-theme="dark"] .sync-status-indicator {
  background: var(--success-color-dark, #064e3b);
  border-color: var(--success-color, #10b981);
}

[data-theme="dark"] .sync-status-indicator.syncing {
  background: var(--warning-color-dark, #451a03);
  border-color: var(--warning-color, #f59e0b);
}

[data-theme="dark"] .interval-select {
  background: var(--surface-color, #374151);
  border-color: var(--border-color, #4b5563);
  color: var(--text-primary, #d1d5db);
}

[data-theme="dark"] .slider {
  background-color: var(--border-color, #4b5563);
}

/* 响应式同步样式 */
@media (max-width: 640px) {
  .sync-status-indicator {
    font-size: 12px;
    padding: 6px 10px;
  }
  
  .interval-select {
    min-width: 100px;
    font-size: 13px;
  }
  
  .sync-btn {
    min-width: 100px;
    font-size: 13px;
    padding: 8px 12px;
  }
}
</style>